package com.cyt.chattlibrary.inputboard;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;

import com.cyt.chattlibrary.R;
import com.cyt.chattlibrary.face.CircleFlowIndicator;
import com.cyt.chattlibrary.face.FaceViewPager;
import com.cyt.chattlibrary.recoder.RecordButton;
import com.cyt.chattlibrary.smoothsoftinputlayout.BaseSoftInputLayout;

/**
 * @author chaowen
 */
public class ChatSoftInputLayout extends BaseSoftInputLayout implements RecordButton.OnFinishedRecordListener {

    private ImageView mIvEmoji;
    private ImageView mIvVoiceText;
    private Animation mShowAnim, mDismissAnim, mShowMoreAnim, mDismissMoreAnim;
    private ImageView mIvMore;
    private View mBtnSend;
    private RecordButton mBtnVoice;
    private EditText mEtText;

    private View container, frame;

    private RecyclerView mList;
    private TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (TextUtils.isEmpty(s) || s.toString().trim().equals("")) {//
                if (mBtnSend.getVisibility() == View.VISIBLE) {
                    dismissSendButton();
                }
            } else {
                if (mBtnSend.getVisibility() != View.VISIBLE) {
                    showSendButton();
                }
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };
    private OnComposeOperationDelegate mDelegate;


    public ChatSoftInputLayout(Context context) {
        this(context, null);
    }


    public ChatSoftInputLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private ChatSoftInputLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ChatSoftInputLayout);
        boolean showVoice = a.getBoolean(R.styleable.ChatSoftInputLayout_showVoice, true);
        boolean showMore = a.getBoolean(R.styleable.ChatSoftInputLayout_showMore, true);
        a.recycle();
        mShowMoreAnim = AnimationUtils.loadAnimation(context, R.anim.chat_show_more_button);

        mDismissMoreAnim = AnimationUtils.loadAnimation(context, R.anim.chat_show_more_button);

        mShowAnim = AnimationUtils.loadAnimation(context, R.anim.chat_show_send_button);
        mShowAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                mBtnSend.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        mDismissAnim = AnimationUtils.loadAnimation(context, R.anim.chat_dismiss_send_button);
        mDismissAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mBtnSend.setVisibility(View.GONE);
                mIvMore.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });

        mEtText.addTextChangedListener(mTextWatcher);

        if (!showVoice) {
            mIvVoiceText.setVisibility(View.GONE);
        }
        if (!showMore) {
            mIvMore.setVisibility(View.GONE);
        }

    }

    @Override
    protected void inflateView() {
        LayoutInflater.from(getContext()).inflate(R.layout.view_chat_compose, this, true);
        mEtText = findViewById(R.id.et_text);
        mBtnSend = findViewById(R.id.btn_send);
        mBtnVoice = findViewById(R.id.btn_voice);
        frame = findViewById(android.R.id.widget_frame);
        mIvVoiceText = findViewById(R.id.iv_voice_text);
        container = findViewById(R.id.rl_bottom);

        mList = findViewById(android.R.id.list);

        mBtnSend.setOnClickListener(this);
        mBtnVoice.setRecorderCallback(this);
        mIvVoiceText.setOnClickListener(this);
        findViewById(R.id.iv_opt_picture).setOnClickListener(this);
        findViewById(R.id.iv_opt_photo).setOnClickListener(this);

        setupEditContain();
        setupEmotionView();
        setupOtherView();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void setupEditContain() {
        View editContain = findViewById(android.R.id.list);
        editContain.setOnTouchListener((v, event) -> {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if (getShowWhat() == SHOW_KEYBOARD || getShowWhat() == SHOW_EMOTION) {
                    hideKeyBoardView();
                    mIvEmoji.setImageResource(R.drawable.btn_emoji_selector);
                }
            }
            return false;
        });
    }

    private void setupEmotionView() {
        mIvEmoji = findViewById(R.id.iv_emoji);
        mIvEmoji.setOnClickListener(this);
        View mLyEmoji = findViewById(R.id.ly_emoji);
        FaceViewPager mViewPager = findViewById(R.id.face_contain);

        CircleFlowIndicator indicator = findViewById(R.id.layout_indicator_point);

        mViewPager.setFlowIndicator(indicator);
        indicator.setCount(mViewPager.getAdapter().getCount());
        mViewPager.setEditText(mEtText);//设置表情输入的界面

        add2ShowViewList(mLyEmoji);
        add2MappingMap(mIvEmoji, SHOW_EMOTION, mLyEmoji);// btnEmotion-(SHOW_EMOTION-emotionView)
    }

    private void setupOtherView() {
        mIvMore = findViewById(R.id.iv_more);
        mIvMore.setOnClickListener(this);
        View mLyOpt = findViewById(R.id.ly_opt);
        add2ShowViewList(mLyOpt);
        add2MappingMap(mIvMore, SHOW_OTHER, mLyOpt);
    }

    @Override
    protected View getContainer() {
        return container;
    }

    @Override
    protected View getFrame() {
        return frame;
    }

    @Override
    public EditText getEditText() {
        return mEtText;
    }

    @Override
    protected View getBtnKeyBoard() {
        return null;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        final int id = v.getId();
        if (id == R.id.btn_send) {
            if (mDelegate != null) {
                mDelegate.onSendText(mEtText.getText().toString());
            }
        } else if (id == R.id.iv_voice_text) {
            if (mBtnVoice.getVisibility() == View.VISIBLE) {
                // Recording,Switch to InputMode
                changeToInput();

                showSoftInput();

                if (mEtText.getText().length() > 0 && mBtnSend.getVisibility() != View.VISIBLE) {
                    showSendButton();
                }
            } else {
                // Switch to VoiceMode
                changeToVoice();

                hideKeyBoardView();

                if (mBtnSend.getVisibility() == View.VISIBLE) {
                    dismissSendButton();
                }
            }
        } else if (id == R.id.iv_opt_picture) {
            if (mDelegate != null) {
                mDelegate.onSendImageClicked(v);
            }
            hideKeyBoardView();
        } else if (id == R.id.iv_opt_photo) {
            if (mDelegate != null) {
                mDelegate.onSendPhotoClicked(v);
            }
            hideKeyBoardView();
        }
    }

    private void changeToInput() {
        mBtnVoice.setVisibility(View.GONE);
        mEtText.setVisibility(View.VISIBLE);
        mIvEmoji.setVisibility(View.VISIBLE);
        mIvVoiceText.setImageResource(R.drawable.btn_to_voice_selector);
    }

    private void changeToVoice() {
        mBtnVoice.setVisibility(View.VISIBLE);
        mEtText.setVisibility(View.GONE);
        mIvEmoji.setVisibility(View.GONE);
        mIvVoiceText.setImageResource(R.drawable.btn_voice_to_text_selector);
    }

    @Override
    protected void changeShowWhat(int showWhat) {
        super.changeShowWhat(showWhat);
        if (getShowWhat() == SHOW_EMOTION) {
            mIvEmoji.setImageResource(R.drawable.btn_emoji_to_text_selector);
        } else if (getShowWhat() == SHOW_KEYBOARD || getShowWhat() == SHOW_OTHER) {
            mIvEmoji.setImageResource(R.drawable.btn_emoji_selector);
            if (getShowWhat() == SHOW_OTHER) {
                changeToInput();
            }
        }
    }

    public RecyclerView getList() {
        return mList;
    }

    private void showSendButton() {
        mIvMore.clearAnimation();
        mIvMore.startAnimation(mDismissMoreAnim);
        mShowAnim.reset();
        mBtnSend.clearAnimation();
        mBtnSend.startAnimation(mShowAnim);
    }

    private void dismissSendButton() {
        mIvMore.clearAnimation();
        mIvMore.startAnimation(mShowMoreAnim);
        mBtnSend.clearAnimation();
        mBtnSend.startAnimation(mDismissAnim);
    }

    @Override
    public void onFinishedRecord(String audioPath, int length) {
        if (mDelegate != null) {
            mDelegate.onSendVoice(audioPath, length);
        }
    }

    public void setOperationDelegate(OnComposeOperationDelegate delegate) {
        mDelegate = delegate;
    }

    public void clearText() {
        if (mEtText != null) {
            mEtText.setText("");
            mEtText.setHint("");
        }
    }

    public void setTextHint(String text) {
        if (mEtText != null) {
            mEtText.setHint(text);
        }
    }

    public interface OnComposeOperationDelegate {
        void onSendText(String text);

        void onSendVoice(String file, int length);

        void onSendImageClicked(View v);

        void onSendPhotoClicked(View view);

        void onSendLocationClicked(View v);
    }


}
